package com.example.myrule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import java.util.List;

public class MyRandomRule extends AbstractLoadBalancerRule {

    public MyRandomRule() {
    }

    // 每台机器访问5次，换下一个服务

    // total=0，默认=0，如果=5，指向下一个服务节点
    // index=0，默认=0，如果total=5，index+1

    // 被调用的次数
    private int total = 0;
    // 当前是谁在提供服务
    private int currentIndex = 0;

    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        } else {
            Server server = null;

            while (server == null) {
                if (Thread.interrupted()) {
                    return null;
                }

                // 获得还活着的服务
                List<Server> upList = lb.getReachableServers();
                // 获得全部的服务
                List<Server> allList = lb.getAllServers();

                int serverCount = allList.size();
                if (serverCount == 0) {
                    return null;
                }

                // 生成区间随机数
                //int index = this.chooseRandomInt(serverCount);
                // 从活着的服务中随机获取一个
                //server = upList.get(index);

                //-===============自定义轮询算法================
                if (total < 4) {
                    server = upList.get(currentIndex);
                    total++;
                } else {
                    total = 0;
                    currentIndex++;
                    if (currentIndex > upList.size() - 1) {
                        currentIndex = 0;
                    }
                    // 从活着的服务中心，获取指定的服务来进行操作
                    server = upList.get(currentIndex);
                }
                //-==========================================

                if (server != null) {
                    if (server.isAlive()) {
                        return server;
                    }

                    server = null;
                }
                Thread.yield();
            }

            return server;
        }
    }

    public Server choose(Object key) {
        return this.choose(this.getLoadBalancer(), key);
    }

    public void initWithNiwsConfig(IClientConfig clientConfig) {
    }
}
